package com.example.stockholdtrack.ui

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.example.stockholdtrack.data.StockApiService
import com.example.stockholdtrack.data.StockDataStore
import com.example.stockholdtrack.data.StockItem
import com.example.stockholdtrack.data.TradingTimeUtils
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import java.util.concurrent.TimeUnit

class StockViewModel(private val dataStore: StockDataStore) : ViewModel() {
    
    private val _stocks = MutableStateFlow<List<StockItem>>(emptyList())
    val stocks: StateFlow<List<StockItem>> = _stocks.asStateFlow()
    
    private val _isLoading = MutableStateFlow(false)
    val isLoading: StateFlow<Boolean> = _isLoading.asStateFlow()
    
    private val stockApiService = StockApiService()
    private var lastStockCount = 0 // 记录上次的股票数量
    
    init {
        // 初始化时先重新计算所有股票数据，然后加载
        viewModelScope.launch {
            dataStore.recalculateAllStockData()
            loadStocks()
        }
    }
    
    private fun loadStocks() {
        viewModelScope.launch {
            _isLoading.value = true
            try {
                // 使用collect来持续监听数据变化
                dataStore.getAllStocks().collect { stockList ->
                    if (!isRefreshing) {
                        _stocks.value = stockList
                        
                        // 检测股票列表变化
                        if (stockList.size != lastStockCount) {
                            println("DEBUG: StockViewModel.loadStocks - 股票列表变化: ${lastStockCount} -> ${stockList.size}")
                            lastStockCount = stockList.size
                        }
                        

                    }
                    _isLoading.value = false
                }
            } catch (e: Exception) {
                _isLoading.value = false
            }
        }
    }
    
    // 添加一个标志来防止loadStocks覆盖refreshStocks的数据
    private var isRefreshing = false
    
    fun addStock(stock: StockItem) {
        viewModelScope.launch {
            try {
                dataStore.insertStock(stock)

            } catch (e: Exception) {
                // 处理异常
            }
        }
    }
    
    fun updateStock(stock: StockItem) {
        viewModelScope.launch {
            dataStore.updateStock(stock)
        }
    }
    
    fun deleteStock(stock: StockItem) {
        viewModelScope.launch {
            dataStore.deleteStock(stock)
        }
    }
    
    fun refreshStocks() {
        isRefreshing = true
        viewModelScope.launch {
            _isLoading.value = true
            try {
                val stockList = dataStore.getAllStocksSync()
                _stocks.value = stockList
                _isLoading.value = false
                isRefreshing = false
                
                // 检测股票列表变化
                if (stockList.size != lastStockCount) {
                    println("DEBUG: StockViewModel.refreshStocks - 股票列表变化: ${lastStockCount} -> ${stockList.size}")
                    lastStockCount = stockList.size
                }
            } catch (e: Exception) {
                _isLoading.value = false
                isRefreshing = false
            }
        }
    }
    
    // 新增：循环请求股价的方法
    fun requestStockPrices() {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                // 设置加载状态为true
                _isLoading.value = true
                
                val currentStocks = _stocks.value
                if (currentStocks.isEmpty()) {
                    println("DEBUG: StockViewModel.requestStockPrices - 股票列表为空，跳过请求")
                    _isLoading.value = false
                    return@launch
                }
                
                println("DEBUG: StockViewModel.requestStockPrices - 开始循环请求股价，股票数量: ${currentStocks.size}")
                
                // 循环请求所有股票价格，间隔300毫秒
                for (stock in currentStocks) {
                    try {
                        val priceData = stockApiService.getStockPrice(stock.code)
                        if (priceData != null) {
                            val updatedStock = stock.copy(
                                currentPrice = priceData.currentPrice
                            )
                            
                            // 更新数据库
                            dataStore.updateStock(updatedStock)
                            
                            println("DEBUG: StockViewModel.requestStockPrices - 更新股票 ${stock.name}(${stock.code}) 价格: ${priceData.currentPrice}")
                        } else {
                            println("DEBUG: StockViewModel.requestStockPrices - 获取股票 ${stock.name}(${stock.code}) 价格失败")
                        }
                    } catch (e: Exception) {
                        println("DEBUG: StockViewModel.requestStockPrices - 更新股票 ${stock.name}(${stock.code}) 异常: ${e.message}")
                    }
                    
                    // 300毫秒间隔
                    delay(300)
                }
                
                // 强制更新内存中的数据，确保UI能收到更新
                val updatedStocks = dataStore.getAllStocksSync()
                _stocks.value = updatedStocks
                
                println("DEBUG: StockViewModel.requestStockPrices - 循环请求股价完成，已更新内存数据")
                println("DEBUG: StockViewModel.requestStockPrices - 更新后的股票数据: ${updatedStocks.map { "${it.name}(${it.code}): ${it.currentPrice}" }}")
                
                // 通知UI线程刷新完成
                _isLoading.value = false
            } catch (e: Exception) {
                println("DEBUG: StockViewModel.requestStockPrices - 循环请求股价异常: ${e.message}")
                _isLoading.value = false
            }
        }
    }
    

    

    
    private suspend fun updateAllStockPrices() {
        val currentStocks = _stocks.value
        if (currentStocks.isEmpty()) return
        
        val updatedStocks = mutableListOf<StockItem>()
        
        for (stock in currentStocks) {
            try {
                val priceData = stockApiService.getStockPrice(stock.code)
                if (priceData != null) {
                    val updatedStock = stock.copy(
                        currentPrice = priceData.currentPrice
                    )
                    updatedStocks.add(updatedStock)
                    
                    // 立即更新数据库
                    dataStore.updateStock(updatedStock)
                    
                    println("DEBUG: StockViewModel.updateAllStockPrices - 更新股票 ${stock.name}(${stock.code}) 价格: ${priceData.currentPrice}")
                } else {
                    updatedStocks.add(stock)
                    println("DEBUG: StockViewModel.updateAllStockPrices - 获取股票 ${stock.name}(${stock.code}) 价格失败")
                }
            } catch (e: Exception) {
                updatedStocks.add(stock)
                println("DEBUG: StockViewModel.updateAllStockPrices - 更新股票 ${stock.name}(${stock.code}) 异常: ${e.message}")
            }
        }
        
        // 更新内存中的数据
        _stocks.value = updatedStocks
    }
    

    
    override fun onCleared() {
        super.onCleared()
    }
    
    class Factory(private val dataStore: StockDataStore) : ViewModelProvider.Factory {
        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            if (modelClass.isAssignableFrom(StockViewModel::class.java)) {
                @Suppress("UNCHECKED_CAST")
                return StockViewModel(dataStore) as T
            }
            throw IllegalArgumentException("Unknown ViewModel class")
        }
    }
} 